#include <fstream>
#include <assert.h>
#include <boost/algorithm/string.hpp>
#include "SystemConfig.h"

using namespace std;
using namespace boost;

namespace common
{
	SystemConfig::SystemConfig(const string& filepath) : filepath_(filepath)
	{
		Load();
	}

	void 
	SystemConfig::Load()
	{
		ifstream fin(filepath_.c_str());
		assert(fin);
		string segmentName;
		string propertyName;
		string line;
		string::size_type pos;

		while (getline(fin, line))
		{
			//删除两端的空格
			trim_copy(line);
			if(line.empty())
				continue;
			if (line[0] == '#')
				continue;
			if (line[0] == '[' && (pos = line.find(']')) != string::npos)
				segmentName = line.substr(1, pos-1);
			else if ((pos = line.find('=')) != string::npos)
			{
				string left;
				string right;
				left = line.substr(0, pos);
				trim_copy(left);
				right = line.substr(pos+1);
				trim_copy(right);
				if (segmentName.empty())
				{
					propertyName = left;
				}
				else
				{
					propertyName = segmentName + "." + left;
				}
				properties_[propertyName] = right;
			}
		}
		fin.close();
	}

	const std::string& 
	SystemConfig::GetProperty(const std::string& name)
	{
		return properties_[name];
	}
}
